/*
 * Copyright (c) 2009 John Pritchard, WTKX Project Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package wtkx.io;

import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

import java.io.Writer;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * 
 * @see XMLHttpRequest
 * @author jdp
 */
public class DOMOutputBuffer
    extends java.io.ByteArrayOutputStream
    implements org.w3c.dom.ls.LSOutput
{

    private String sid;
    private Charset enc;
    private java.io.Writer writer;


    public DOMOutputBuffer(Document doc, URL url, Charset enc){
        super();

        this.sid = url.toExternalForm();

        this.enc = enc;

        DOMImplementation dom = doc.getImplementation();
        if (dom instanceof DOMImplementationLS){
            DOMImplementationLS dls = (DOMImplementationLS)dom;
            LSSerializer serializer = dls.createLSSerializer();
            try {
                serializer.write(doc,this);
            }
            catch (org.w3c.dom.ls.LSException exc){
                throw new IllegalStateException("Failed to write document",exc);
            }
        }
        else
            throw new IllegalStateException("Requires Documents in DOM Core '3.0' with LS.");
    }


    public Writer getCharacterStream(){
        Writer writer = this.writer;
        if (null == writer){
            Charset enc = this.enc;
            if (null != enc){
                writer = new OutputStreamWriter(this,enc);
            }
            else
                writer = new OutputStreamWriter(this);

            this.writer = writer;
        }
        return writer;
    }
    public void setCharacterStream(java.io.Writer writer){
        this.writer = writer;
    }
    public java.io.OutputStream getByteStream(){
        return this;
    }
    public void setByteStream(java.io.OutputStream stream){
    }
    public String getSystemId(){
        return sid;
    }
    public void setSystemId(String sid){
    }
    public String getEncoding(){
        Charset enc = this.enc;
        if (null != enc)
            return enc.name();
        else
            return null;
    }
    public void setEncoding(String enc){
    }
}
